﻿using Newtonsoft.Json.Linq;
using System;
using System.Net;
using WebSocketSharp;

namespace CommonUtils
{
    public class WebSocketClient : WebSocket
    {
        public event Action<string> OnMessageReceive;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="url">ws://hist:port/route</param>
        public WebSocketClient(string url) : base(url)
        {
            OnError += delegate
            {
                LogUtil.PrintInfo("WebSocket客户端({0})异常!", Url);
            };

            OnOpen += delegate
            {
                LogUtil.PrintInfo("WebSocket客户端({0})连接成功!", Url);
            };

            OnMessage += delegate (object sender, MessageEventArgs e)
            {
                LogUtil.PrintInfo("WebSocket客户端({0})收到消息，长度{1} !", Url, e.Data.Length);
                OnMessageReceive?.Invoke(e.Data);
            };

            OnClose += delegate
            {
                LogUtil.PrintInfo("WebSocket客户端({0})断开连接!", Url);
            };

            LogUtil.PrintInfo("WebSocket客户端({0})已创建!", url);
        }

        public WebSocketClient(IPEndPoint iep, string route) : this("ws://" + iep + (route[0] == '/' ? route : ("/" + route))) { }

        public JObject Status
        {
            get
            {
                var status = new JObject();
                status.Add("Url", Url);
                status.Add("IsSecure", IsSecure);
                status.Add("IsAlive", IsAlive);
                return status;
            }
        }

        public void Start()
        => Connect();

        public void Open()
        => Connect();

        long _reconnectCount;

        public void OpenReconnect()
        {
            OnClose += delegate
            {
                LogUtil.PrintInfo("WebSocket客户端({0})将在10秒后进行第{1}次断线重连！", Url, ++_reconnectCount);
                ThreadUtil.SleepSeconds(10);
                Start();
            };
            LogUtil.PrintInfo("WebSocket客户端({0})已开启断线重连！", Url);
        }

        public Action<string> OnSend;

        public new void Send(string data)
        {
            LogUtil.PrintInfo("WebSocket客户端({0})发送消息，长度{1}!", Url, data.Length);
            OnSend?.Invoke(data);
            base.Send(data);
        }
    }
}
